$(document).ready(function(){
        $(".addNode").click(function(){
                //NODE TYPE(orgchart or workflow)
                node_type = $(this).attr("type");
                
                //Append the node and make it draggable
                createNode("#droppable",node_type)
        })
        //Hover of circle
        $("body").on("mouseenter","circle",function(){
            $(this).attr("fill","#ec9f2e")
        })
        $("body").on("mouseout","circle",function(){
            $(this).attr("fill","gray")
        })
        var ctrNode = parseInt($(".startCtr").val())
        function createNode(container,node_type){
                nodeData = "";
                var toSave = {};
                switch(node_type){
                        case "1":
                                toSave['processor_type'] = '0';
                                toSave['processor'] = '0';
                                toSave['buttons'] = '0';
                                break;
                        case "2":
                                toSave['dept'] = 'NODE '+ctrNode+'';
                                toSave['orgChartHead'] = '';
                                toSave['orgChartAsstHead'] = '';
                                toSave['orgChartMembers'] = '';
                                break;
                }
                var json = JSON.stringify(toSave);
                $(container).append(setNode(ctrNode,node_type,"NODE "+ctrNode+"","100px","20px","","",json));
                //interaction of nodes
                nodeInteraction()
                //increment the suffix for unique id
                ctrNode++;
                //add warning on reloading the page
                fire_onBeforeOnload(1)
        }
})
function setNode(ctrNode,node_type,text,top,left,height,width,json){
        return '<div class="outerNode" id="node_'+ctrNode+'" style="top:'+top+';left:'+left+';float: left;position: absolute;width: auto;z-index:3" ondblclick="getNodeProperty(this)" node-type="'+node_type+'"'+
                            "node_data='"+json+"'>"+
                                '<img class="deleteNode" src="/images/delete.gif" style="top:0px;vertical-align:top;cursor:pointer;float:left" id="del_'+ctrNode+'" onclick="deleteNode(this)">'+
                                '<div class="node node_design node_square" id="innerNode_'+ctrNode+'" style="height:'+height+';width:'+width+';">'+
                                        '<div class="nodeLabel" id="nodeLabel_'+ctrNode+'">'+text+'</div>'+
                                '</div>'+
                                '<div class="circle_drop" id="drop_'+ctrNode+'">'+
                                        '<svg style="position:absolute;left:0px;top:0px" width="18" height="18" pointer-events="all" position="relative" version="1.1" xmlns="http://www.w3.org/1999/xhtml">'+
                                                '<circle cx="9" cy="9" r="9" version="1.1" xmlns="http://www.w3.org/1999/xhtml" style="" fill="gray" stroke="none"></circle>'+
                                        '</svg>'+
                                '</div>'+
                            '</div>'
}
function deleteNode(obj){
        var ans = confirm("Are you sure you want to delete this object?");
        if(ans==true){
                id = obj.id.split("_")[1];
                if("node_"+id==$(".greenNode").attr("id")){
                        //remove the propoerties
                        $("#node_id").val(null);
                        $(".nodeDepartment").val(null);
                        $(".nodeHeight").val(null);
                        $(".nodeWidth").val(null);
                        $(".orgchartDeptUsers").html(null);
                }
                $(obj).parent().remove();
                $(".lines").each(function(){
                        if($(this).attr("parent") == "node_"+id || $(this).attr("child") == "node_"+id ){
                                $(this).remove()
                        }
                })
        }
}
function createLine(parent_id,child_id,appendTo){
        if(checkLineConnect(child_id,parent_id)>0){
                return false;
        }else{
                //generate class of lines
                parent = convToIntSubstr(parent_id,5,0);
                child = convToIntSubstr(child_id,5,0);
                lineClass = "line_"+parent+"_"+child;
                //parent x and y
                parentTop = getPositionOnNode($("#"+parent_id).css("top"),$("#"+parent_id).css("height"));
                parentLeft = getPositionOnNode($("#"+parent_id).css("left"),$("#"+parent_id).css("width"));
                //child
                childTop = getPositionOnNode($("#"+child_id).css("top"),$("#"+child_id).css("height"));
                childLeft = getPositionOnNode($("#"+child_id).css("left"),$("#"+child_id).css("width"));
                //middle horizontal
                midTop = getPositionMiddleTop(parentTop,childTop);
                //validate negative middle left position
                midLeft = validatePosition(parentLeft,childLeft);
                //validate negative top position
                verticalParentTop = validatePosition(parentTop,midTop);
                verticalChildTop = validatePosition(childTop,midTop);
                //height
                verticalParentHeight = parentTop-midTop;
                verticalParentHeight = parseInt(isNeg(verticalParentHeight))+5
                verticalChildHeight = childTop-midTop;
                verticalChildHeight = parseInt(isNeg(verticalChildHeight))+5
                horizontalMiddleWidth = parentLeft-childLeft;
                horizontalMiddleWidth = parseInt(isNeg(horizontalMiddleWidth))+5
                //execute!!
                $(appendTo).append(verticalParent(lineClass,parent_id,child_id,verticalParentTop,parentLeft,verticalParentHeight,lineClass)+
                                   verticalChild(lineClass,parent_id,child_id,verticalChildTop,childLeft,verticalChildHeight,lineClass)+
                                   horizontalMiddle(lineClass,parent_id,child_id,midTop,midLeft,horizontalMiddleWidth,lineClass));
                return true;
        }
}
/*Specific for every drop*/
function verticalParent(lineClass,parent_id,child_id,verticalParentTop,parentLeft,verticalParentHeight,rel){
        return '<div class="lines vertical verticalParent '+lineClass+'" parent="'+parent_id+'" child="'+child_id+'" style="top:'+verticalParentTop+'px;left:'+parentLeft+'px;height:'+verticalParentHeight+'px;z-index:0" rel="'+rel+'" onclick="deleteLine(this)"></div>';
}
function verticalChild(lineClass,parent_id,child_id,verticalChildTop,childLeft,verticalChildHeight,rel){
        return '<div class="lines vertical verticalChild '+lineClass+'" parent="'+parent_id+'" child="'+child_id+'" style="top:'+verticalChildTop+'px;left:'+childLeft+'px;height:'+verticalChildHeight+'px;z-index:0" rel="'+rel+'" onclick="deleteLine(this)"></div>';
}
function horizontalMiddle(lineClass,parent_id,child_id,midTop,midLeft,horizontalMiddleWidth,rel){
        return '<div class="lines horizontal horizontalMiddle '+lineClass+'" parent="'+parent_id+'" child="'+child_id+'" style="top:'+midTop+'px;left:'+midLeft+'px;width:'+horizontalMiddleWidth+'px;z-index:0" rel="'+rel+'" onclick="deleteLine(this)"></div>';
}
/*Specific for getting the lines for db*/
function setLineIndiv(lineClass,parent_id,child_id,top,left,height,width,rel){
        return '<div class="'+lineClass+'" parent="'+parent_id+'" child="'+child_id+'"'+
                'style="top:'+top+'px;left:'+left+'px;height:'+height+'px;z-index:0;width:'+width+'px" '+
                'rel="'+rel+'" onclick="deleteLine(this)"></div>';
}
function deleteLine(obj){
        var ans = confirm("Are you sure you want to delete this connection?");
        if(ans==true){
                var lineClass = $(obj).attr("rel");
                $("."+lineClass).each(function(){
                        $(this).remove();
                })
        }
}
function getPositionMiddleTop(parentTop,childTop){
        return (parentTop+childTop)/2;
}

function validatePosition(parent,child){
        left = parent-child
        if(isNaN(convToIntSubstr(left.toString(),0,left.toString().length-1))){
                return parent;
        }else{
                return child;
        }
}

function getPositionOnNode(pos,size){
        size_2 = convToIntSubstr(size,0,2)/2;
        position = size_2+convToIntSubstr(pos,0,2);
        return position;
}

function convToIntSubstr(str,start,substrMinus){
        return parseInt(str.substr(start,str.length-parseInt(substrMinus)));
}
//check if negative val
function isNeg(val){
        val = val.toString();
        if(isNaN(convToIntSubstr(val,0,val.length-1))){
                return val.substr(1,val.length);
        }else{
                return val;
        }
}
//check if the line connected
function checkLineConnect(child_id,parent_id){
        parent = convToIntSubstr(parent_id,5,0);
        child = convToIntSubstr(child_id,5,0);
        lineClassParent = "line_"+parent+"_"+child;
        lineClassChild = "line_"+child+"_"+parent;
        errorCount = 0;
        $(".lines").each(function(){
                if($(this).hasClass(lineClassParent) || $(this).hasClass(lineClassChild)){
                        errorCount++;
                }
        })
        return errorCount;
}
function nodeInteraction(){
        //Set the node as draggable
        $(".outerNode").draggable(
                {
                        containment:'#droppable'
                },
                {
                        drag: function(){
                                moveLines(this.id);
                        }
                }
        );
        //Set the circle as draggable
        $(".circle_drop").draggable(
                {
                        revert: "valid"
                },
                {
                        containment:'#droppable'
                }
        )
        //set the workspace as droppable for the circle
        $("#droppable").droppable();
            
        //Get the parent node
        $(".outerNode").mousedown(function(){
            //Drop the object
            parent_id = this.id
            $(".outerNode").droppable({
                    //Get the child node
                    hoverClass: function(){
                        //line class
                        child_id = this.id;
                        if(checkLineConnect(child_id,parent_id)==0){
                                if(child_id!=parent_id){
                                        return "hoverNode";
                                }else{
                                        return "";
                                }
                        }else{
                                return "hoverNodeWarning";
                        }
                        
                    },
                    accept: ".circle_drop",
                    drop: function( event, ui ) {
                        child_id = this.id;
                        if(child_id!=parent_id){
                            if(createLine(parent_id,child_id,"#droppable")!=false){
                                    createLine(parent_id,child_id,"#droppable")
                            }else{
                                    alert("error")
                            }
                        }
                    }
            });
            //Manipulating the z-index
            $(".outerNode").css("z-index",1);
            $("#"+parent_id).css("z-index",2);
        })
}
//on moving the node
function moveLines(id){
        $(".lines").each(function(){
                if($(this).attr("parent")==id || $(this).attr("child")==id){
                        child_id = $(this).attr("child");
                        parent_id = $(this).attr("parent");
                        parentTop = getPositionOnNode($("#"+parent_id).css("top"),$("#"+parent_id).css("height"));
                        parentLeft = getPositionOnNode($("#"+parent_id).css("left"),$("#"+parent_id).css("width"));
                        //child
                        childTop = getPositionOnNode($("#"+child_id).css("top"),$("#"+child_id).css("height"));
                        childLeft = getPositionOnNode($("#"+child_id).css("left"),$("#"+child_id).css("width"));
                        //middle horizontal
                        midTop = getPositionMiddleTop(parentTop,childTop);
                        //validate negative middle left position
                        midLeft = validatePosition(parentLeft,childLeft);
                        //validate negative top position
                        verticalParentTop = validatePosition(parentTop,midTop);
                        verticalChildTop = validatePosition(childTop,midTop);
                        //height
                        verticalParentHeight = parentTop-midTop;
                        verticalParentHeight = parseInt(isNeg(verticalParentHeight))+5
                        verticalChildHeight = childTop-midTop;
                        verticalChildHeight = parseInt(isNeg(verticalChildHeight))+5
                        horizontalMiddleWidth = parentLeft-childLeft;
                        horizontalMiddleWidth = parseInt(isNeg(horizontalMiddleWidth))+5
                        if($(this).hasClass('verticalParent')){
                                $(this).css({
                                        "top":verticalParentTop,
                                        "height":verticalParentHeight,
                                        "left":parentLeft
                                })
                        }else if($(this).hasClass('verticalChild')){
                                $(this).css({
                                        "top":verticalChildTop,
                                        "height":verticalChildHeight,
                                        "left":childLeft
                                })
                        }else if($(this).hasClass('horizontalMiddle')){
                                $(this).css({
                                        "top":midTop,
                                        "left":midLeft,
                                        "width":horizontalMiddleWidth
                                })
                        }
                }
        })
}
function fire_onBeforeOnload(status){
    /*if(status==0){
        window.onbeforeunload = function () {
            // blank function do nothing
        }
    }else{
        window.onbeforeunload = function(e) {
            return 'You will lose any unsaved edits';
        };
    }*/
}